package com.wing.cms.service;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wing.cms.dao.ArticleDao;
import com.wing.cms.dao.SiteDao;
import com.wing.cms.domain.Site;
import com.wing.common.util.ApplicationPath;
import com.wing.common.util.GUID;
import com.wing.common.util.PageBean;
import com.wing.sys.domain.Auth;
import com.wing.sys.service.AuthManager;

/**
 * 
 * @author wyf
 * 
 */
@Service
@Transactional
public class SiteManager {
	@Autowired
	private SiteDao sitedao;
	@Autowired
	private ArticleDao articleDao;
	
	@Autowired
	private AuthManager rightManager;

	/**
	 * 获得该对象所有数据的列表
	 * 
	 * @return list
	 */
	public List<Map<String, Object>> findAll() {
		return sitedao.findAll();
	}

	public PageBean findPageList(int currentPage, int pageSize, String seachv) {
		return sitedao.findPageList(currentPage, pageSize,seachv);
	}

	/**
	 * 通过id得到对象
	 * 
	 * @param id
	 * @return pObject
	 */
	public Site findById(String id) {
		return sitedao.findById(id);
	}
	public List<Map<String, Object>>  getSitesBySitePath(String path) {
		return sitedao.getSitesBySitePath(null, path);
	}
	
	
	/**
	 * 保存对象
	 * 
	 * @param site
	 * @param sitemgrId
	 */
	public void saveSite(Site site, String sitemgrId) {
		if (site.getId() == null || "".equals(site.getId())) {
			site.setId(new GUID().toString());
			site.setCreate_time(new Date());
			sitedao.insert(site);
			if (sitemgrId != null && !"".equals(sitemgrId)) {
				Auth r = new Auth();
				r.setId(new GUID().toString());
				r.setOwner_id(sitemgrId);
				r.setRes_id(site.getId());
				r.setType(Auth.TYPE_SITE);
				rightManager.insert(r);
			}
		} else {
			site.setCreate_time(new Date());
			sitedao.update(site);
			if (sitemgrId != null && !"".equals(sitemgrId)) {
				List auths = rightManager.getAuthsByTypeResId(Auth.TYPE_SITE,
						site.getId());
				Auth r = null;
				if (auths.size() == 0) {
					r = new Auth();
					r.setId(new GUID().toString());
					r.setRes_id(site.getId());
					r.setType(Auth.TYPE_SITE);
					r.setOwner_id(sitemgrId);
					rightManager.insert(r);
				} else {
					r = (Auth) auths.get(0);
					r.setOwner_id(sitemgrId);
					rightManager.update(r);
				}
			}
		}
	}

	/**
	 * 编辑对象
	 * 
	 * @param site
	 */
	public void updateSite(Site site) {
		sitedao.update(site);
	}

	
	/**
	 * 删除对象
	 * 
	 * @param chk
	 *            对象id数组
	 */
	public void deleteSites(String[] chk) {
		for (int i = 0; i < chk.length; i++) {
			File delFlie = new File(ApplicationPath.getParameter("appRoot")+"/site/"+sitedao.findById(chk[i]).getSite_path());
			if(delFlie.exists())
				try {
					FileUtils.deleteDirectory(delFlie);
				} catch (IOException e) {
					e.printStackTrace();
				}
				String del$cms_site$_sql = "delete from  cms_site where id = '"+chk[i]+"'";
				String del$sys_auth$_sql = "delete from  sys_auth where res_id = '"+chk[i]+"' and type = 'site' ";
				String del$sys_auth$_sql1 = "delete from  sys_auth where owner_id = '"+chk[i]+"'";
				String del$cms_channel$_sql = "delete from  cms_channel where site_id ='"+chk[i]+"'";
				String del$cms_artgrou$_sql = "delete from  cms_artgroup where site_id ='"+chk[i]+"'";
				String del$cms_article$_sql = "delete from  cms_article where site_id ='"+chk[i]+"'";
				String del$cms_article_group$_sql = "delete from  cms_article_group where artgroup_id in(select id from cms_artgroup where site_id ='"+chk[i]+"')";
				String del$cms_placeholder$_sql = "delete from  cms_placeholder where channelid in(select id from cms_channel where site_id ='"+chk[i]+"')";
				String del$cms_portletinstance$_sql = "delete from  cms_portletinstance where id in(select portletId from cms_placeholder where channelid in (select id from cms_channel where site_id ='"+chk[i]+"'))";
				String del$cms_portletinstance1$_sql = "delete from  cms_portletinstance1 where id in(select portletId from cms_placeholder where channelid in (select id from cms_channel where site_id ='"+chk[i]+"'))";
				String del$cms_portletinstance2$_sql = "delete from  cms_portletinstance2 where id in(select portletId from cms_placeholder where channelid in (select id from cms_channel where site_id ='"+chk[i]+"'))";
				String del$cms_portletinstance3$_sql = "delete from  cms_portletinstance3 where id in(select portletId from cms_placeholder where channelid in (select id from cms_channel where site_id ='"+chk[i]+"'))";
				String del$cms_portletinstance4$_sql = "delete from  cms_portletinstance4 where id in(select portletId from cms_placeholder where channelid in (select id from cms_channel where site_id ='"+chk[i]+"'))";
				String del$ext_productgroup$_sql = "delete from  ext_productgroup where site_id ='"+chk[i]+"'";
				String del$ext_products$_sql = "delete from  ext_products where site_id ='"+chk[i]+"'";
				String del$cms_layout$_sql = "delete from  cms_layout where ispub ='0' and id in(select res_id from sys_auth where owner_id ='"+chk[i]+"')";
				String del$cms_template$_sql = "delete from  cms_template where ispub ='0' and id in(select res_id from sys_auth where owner_id ='"+chk[i]+"')";
				String del$cms_lookfeel$_sql = "delete from  cms_lookfeel where ispub ='0'and id in(select res_id from sys_auth where owner_id ='"+chk[i]+"')";
			//删除产品和文章全文展示信息
				String del$cms_placeholder$_sql1 = "delete from  cms_placeholder where channelid like '%,"+chk[i]+"'";
				String del$cms_portletinstance$_sql1 = "delete from  cms_portletinstance where id in(select portletId from cms_placeholder where channelid  like '%,"+chk[i]+"')";
				String del$cms_portletinstance1$_sql2 = "delete from  cms_portletinstance1 where id in(select portletId from cms_placeholder where channelid like '%,"+chk[i]+"')";
				String del$cms_portletinstance2$_sql1 = "delete from  cms_portletinstance2 where id in(select portletId from cms_placeholder where channelid like '%,"+chk[i]+"')";
				String del$cms_portletinstance3$_sql1 = "delete from  cms_portletinstance3 where id in(select portletId from cms_placeholder where channelid like '%,"+chk[i]+"')";
				String del$cms_portletinstance4$_sql1 = "delete from  cms_portletinstance4 where id in(select portletId from cms_placeholder where channelid  like '%,"+chk[i]+"')";

				
				String[] sqls = new String[24];
				sqls[0] = del$cms_site$_sql;
				sqls[1] = del$cms_article$_sql;
				sqls[2] = del$cms_article_group$_sql;
				sqls[3] = del$cms_artgrou$_sql;
				sqls[4] = del$cms_portletinstance$_sql;
				sqls[5] = del$cms_portletinstance1$_sql;
				sqls[6] = del$cms_portletinstance2$_sql;
				sqls[7] = del$cms_portletinstance3$_sql;
				sqls[8] = del$cms_portletinstance4$_sql;
				sqls[9] = del$cms_placeholder$_sql;
				sqls[10] = del$ext_productgroup$_sql;
				sqls[11] = del$ext_products$_sql;
				sqls[12] = del$cms_layout$_sql;
				sqls[13] = del$cms_template$_sql;
				sqls[14] = del$cms_lookfeel$_sql;
				sqls[15] = del$cms_channel$_sql;
				sqls[16] = del$sys_auth$_sql;
				sqls[17] = del$sys_auth$_sql1;
				
				sqls[18] = del$cms_portletinstance$_sql1;
				sqls[19] = del$cms_portletinstance1$_sql2;
				sqls[20] = del$cms_portletinstance2$_sql1;
				sqls[21] = del$cms_portletinstance3$_sql1;
				sqls[22] = del$cms_portletinstance4$_sql1;
				sqls[23] = del$cms_placeholder$_sql1;
				
//				for(int i = 0; i < sqls.length;i++){
//					System.out.println(sqls[i]);
//				}
				sitedao.cloneSite(sqls);
		}
	}

	/**
	 * 获得站点管理员是该用用户的站点
	 * @param userId
	 * @return
	 */
	public List getSitesBySiteMgrs(String userId) {
		return sitedao.getSitesBySiteMgrs(userId);
	}
	/**
	 * 获得站点成员是该用用户的站点
	 * @param userId
	 * @return
	 */
	public List getSitesBySiteUser(String userId) {
		return sitedao.getSitesBySiteUser(userId);
	}

	public boolean checkSitePathRepeat(String siteId,String sitePath) {
		if(siteId==null){
			List<String> sites = new ArrayList();
			sites.add("ybl");
			sites.add("qzw");
			sites.add("demo");
			sites.add("www");
			sites.add("example");
			sites.add("test");
			for(int i=0;i<sites.size();i++){
				if(sitePath.indexOf(sites.get(i))!=-1){
					return true;
				}
			}
		}
		List list = sitedao.getSitesBySitePath(siteId, sitePath);
		if (list.size() > 0)
			return true;
		return false;

	}

	public void bakSite(String id) {
		sitedao.creatBakSiteSQL(id);
	}
	
	/**
	 * 复制一个站点
	 * 
	 * @param site
	 */
	public void cloneSite(String srcSitePath, String destSitePath,String destSiteUrl,
			String destSiteName, String userId,String rodmomCPId) {
		Map<String, Object> oldSite = (Map<String, Object>) sitedao.getSitesBySitePath(null, srcSitePath).get(0);
		String newSiteId = new GUID().toString();
		//**************************站点频道布局的相关信息***********************************
		java.util.Date now = new java.util.Date();     
	     SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );    
	     String sdate=sdf.format(now).toString();   
		String insert_$cms_site$_sql = "INSERT INTO cms_site VALUES ('"
				+ newSiteId + "','" + destSiteName + "','" + destSitePath
				+ "','" + destSiteUrl + "',0,1000,0,'复制自"
				+ srcSitePath + "',0,'"+sdate+"')";
		String insert_$sys_auth$_sql = "INSERT INTO sys_auth VALUES ('"
				+ new GUID().toString() + "','" + userId + "','" + newSiteId
				+ "','site')";
		String insert_$sys_auth$_sql1 = "INSERT INTO sys_auth (select concat('"+rodmomCPId+"',id),'"+newSiteId+"',concat('"+rodmomCPId+"',res_id),type from sys_auth where owner_id= '"+oldSite.get("id")+"')";
		String insert_$cms_channel$_sql = "insert into cms_channel (select concat('"+rodmomCPId+"',id),IF(pid = 'ROOT','ROOT',concat('"+rodmomCPId+"',pid)),'"
				+ newSiteId+ "',channel_name,concat('"+rodmomCPId+"',lookandfeel),concat('"+rodmomCPId+"',layout),order_num," +
						"valid_flag,remarks,status,ispub  from cms_channel" +" where site_id = '"+ oldSite.get("id") + "')";
		String insert_$cms_layout$_sql = "insert into cms_layout (select concat('"+rodmomCPId+"',id),name,filename,order_num,ispub from cms_layout "+
					"where id in (select res_id from sys_auth where type = 'layout'  and owner_id = '"+ oldSite.get("id") + "'))";
		String insert_$cms_lookfeel$_sql = "insert into cms_lookfeel (select concat('"+rodmomCPId+"',id),name,filename,order_num,ispub from cms_lookfeel "+
		"where id in (select res_id from sys_auth where type = 'lookfeel'  and owner_id = '"+ oldSite.get("id") + "'))";
		String insert_$cms_template$_sql = "insert into cms_template (select concat('"+rodmomCPId+"',id),name,type,picpath,ftlpath,pictype,ispub from cms_template "
				+" where id in (select res_id from sys_auth where type = 'template'  and owner_id = '"+ oldSite.get("id") + "'))";
		String insert_$cms_function$_sql = "insert into cms_function (select concat('"+rodmomCPId+"',id),name,editview,ftlpath,fun_code,status,ispub,pictype,picpath,classz from cms_function "
		+" where id in (select res_id from sys_auth where type = 'function'  and owner_id = '"+ oldSite.get("id") + "'))";
		 //**********************************文章相关信息*****************************************
		String insert_$cms_artgroup$_sql = "insert into cms_artgroup(select concat('"+rodmomCPId+"',id),IF(pid = 'ROOT','ROOT',concat('"+rodmomCPId+"',pid))," +
		"'"+newSiteId+"',name,status,order_num,valid_flag,remarks from cms_artgroup t where t.site_id='"+ oldSite.get("id") + "')";
		String insert_$cms_article_group$_sql = "insert into cms_article_group(select concat('"+rodmomCPId+"',id)," +
		" concat('"+rodmomCPId+"',article_id), concat('"+rodmomCPId+"',artgroup_id),publish_state,post_time,post_user,istop,toptime,valid_flag " +
		"from cms_article_group where  article_id in (select id from cms_article where site_id = '"+ oldSite.get("id") + "'))";
		//*********************************产品相关表***************************************
		String insert_$ext_productgroup$_sql = "insert into ext_productgroup (select concat('"+rodmomCPId+"',id),IF(pid = 'ROOT','ROOT',concat('"+rodmomCPId+"',pid))," +
		"'"+newSiteId+"',name,status,order_num,valid_flag,remarks from ext_productgroup t where t.site_id='"+ oldSite.get("id") + "' )";
		String insert_$ext_products$_sql = "insert into ext_products (select concat('"+rodmomCPId+"',id),concat('"+rodmomCPId+"',groupid),'"+newSiteId+"',product_name," +
		"product_code,keyword,introduction,inventory,promotion,price,picpath,create_user,create_time,valid_flag,small_picpath" +
		" from ext_products t where t.site_id= '"+ oldSite.get("id") + "')";
		//******************复制portlet相关信息**************************************************
		String insert_$cms_placeholder$_sql = "insert into cms_placeholder (select concat('"+rodmomCPId+"',id)," +
		"placeholderid,concat('"+rodmomCPId+"',channelid),concat('"+rodmomCPId+"',portletId), " +
		" concat('"+rodmomCPId+"',layoutId),portletype,order_num from cms_placeholder where  channelid in (select id from cms_channel" +
		" where site_id =  '"+ oldSite.get("id") + "'))";
		String insert_$cms_portletinstance$_sql = "insert into cms_portletinstance (select concat('"+rodmomCPId+"',id),IF(artgroupId = 'ROOT','ROOT',concat('"+rodmomCPId+"',artgroupId)),isnavi," +
		"showlevel,IF(assoportlet = '','',concat('"+rodmomCPId+"',assoportlet)),showstate,titlelength,articlecount,summarylength, concat('"+rodmomCPId+"',templateid)," +
		" title ,portletwidth,portletheight,titlecolor,titlepic,titletype from cms_portletinstance where id in " +
		"(select portletId from cms_placeholder where  channelid in (select id from cms_channel" +
		" where site_id = '"+ oldSite.get("id") + "')))";
		String insert_$cms_portletinstance1$_sql = "insert into cms_portletinstance1 (select  concat('"+rodmomCPId+"',id),IF(menuchannelId = 'ROOT','ROOT',concat('"+rodmomCPId+"',menuchannelId)),showlevel," +
		"isopened,showstate,concat('"+rodmomCPId+"',templateid),title,titlecolor,portletwidth,portletheight,titlepic,titletype from cms_portletinstance1 where id in " +
		"(select portletId from cms_placeholder where  channelid in (select id from cms_channel " +
		" where site_id = '"+ oldSite.get("id") + "')))";
		String insert_$cms_portletinstance2$_sql = "insert into cms_portletinstance2 (select  concat('"+rodmomCPId+"',id),IF(productgroupId = 'ROOT','ROOT',concat('"+rodmomCPId+"',productgroupId))," +
		"isnavi,showlevel,IF(assoportlet = '','',concat('"+rodmomCPId+"',assoportlet)),showstate,titlelength,productcount,summarylength,concat('"+rodmomCPId+"',templateid)," +
		"title,portletwidth,portletheight,titlecolor,titlepic,titletype from cms_portletinstance2 where id in " +
		"(select portletId from cms_placeholder where  channelid in (select id from cms_channel " +
		" where site_id = '"+ oldSite.get("id") + "')))";
		String insert_$cms_portletinstance3$_sql = "insert into cms_portletinstance3 (select  concat('"+rodmomCPId+"',id),showcontent," +
		"contentlength,contentsytle,cssname,concat('"+rodmomCPId+"',templateid),title,titlecolor,showstate,portletwidth,portletheight,titlepic,titletype" +
		" from cms_portletinstance3 where id in " +
		"(select portletId from cms_placeholder where  channelid in (select id from cms_channel " +
		" where site_id = '"+ oldSite.get("id") + "')))";
		String insert_$cms_portletinstance4$_sql = "insert into cms_portletinstance4 (select  concat('"+rodmomCPId+"',id),picpath," +
		"picwidth,picheight,picsytle,cssname,concat('"+rodmomCPId+"',templateid),title,titlecolor,showstate,portletwidth,portletheight,titlepic,titletype" +
		" from cms_portletinstance4 where id in " +
		"(select portletId from cms_placeholder where  channelid in (select id from cms_channel " +
		" where site_id = '"+ oldSite.get("id") + "')))";
		String insert_$cms_portletinstancec$_sql = "insert into cms_portletinstance_c (select  concat('"+rodmomCPId+"',id),concat('"+rodmomCPId+"',templateid)," +
		"title,titlecolor,portletwidth,portletheight,titlepic,titletype,object,objecttype" +
		" from cms_portletinstance_c where id in " +
		"(select portletId from cms_placeholder where  channelid in (select id from cms_channel " +
		" where site_id = '"+ oldSite.get("id") + "')))";
		//******************复制产品展示和新闻展示的相关信息**************************************************
		String insert_$cms_placeholder$_sql1 = "insert into cms_placeholder (select concat('"+rodmomCPId+"',id),placeholderid,replace(channelid,',"+oldSite.get("id")+"',',"+newSiteId
		+"'),concat('"+rodmomCPId+"',portletId),layoutId,portletype,order_num from cms_placeholder where channelid like '%,"+ oldSite.get("id") + "')"; 
		String insert_$cms_portletinstance$_sql1 = "insert into cms_portletinstance (select concat('"+rodmomCPId+"',id),IF(artgroupId = 'ROOT','ROOT',concat('"+rodmomCPId+"',artgroupId)),isnavi," +
		"showlevel,IF(assoportlet = '','',concat('"+rodmomCPId+"',assoportlet)),showstate,titlelength,articlecount,summarylength, concat('"+rodmomCPId+"',templateid)," +
		" title ,portletwidth,portletheight,titlecolor,titlepic,titletype from cms_portletinstance where id in " +
		"(select portletId from cms_placeholder where  channelid like '%," + oldSite.get("id")+"'))";
		String insert_$cms_portletinstance1$_sql1 = "insert into cms_portletinstance1 (select  concat('"+rodmomCPId+"',id),IF(menuchannelId = 'ROOT','ROOT',concat('"+rodmomCPId+"',menuchannelId)),showlevel," +
		"isopened,showstate,concat('"+rodmomCPId+"',templateid),title,titlecolor,portletwidth,portletheight,titlepic,titletype from cms_portletinstance1 where id in " +
		"(select portletId from cms_placeholder where  channelid like '%," + oldSite.get("id")+"'))";
		String insert_$cms_portletinstance2$_sql1 = "insert into cms_portletinstance2 (select  concat('"+rodmomCPId+"',id),IF(productgroupId = 'ROOT','ROOT',concat('"+rodmomCPId+"',productgroupId))," +
		"isnavi,showlevel,IF(assoportlet = '','',concat('"+rodmomCPId+"',assoportlet)),showstate,titlelength,productcount,summarylength,concat('"+rodmomCPId+"',templateid)," +
		"title,portletwidth,portletheight,titlecolor,titlepic,titletype from cms_portletinstance2 where id in " +
		"(select portletId from cms_placeholder where  channelid  like '%," + oldSite.get("id")+"'))";
		String insert_$cms_portletinstance3$_sql1 = "insert into cms_portletinstance3 (select  concat('"+rodmomCPId+"',id),showcontent," +
		"contentlength,contentsytle,cssname,concat('"+rodmomCPId+"',templateid),title,titlecolor,showstate,portletwidth,portletheight,titlepic,titletype" +
		" from cms_portletinstance3 where id in " +
		"(select portletId from cms_placeholder where  channelid  like '%," + oldSite.get("id")+"'))";
		String insert_$cms_portletinstance4$_sql1 = "insert into cms_portletinstance4 (select  concat('"+rodmomCPId+"',id),picpath," +
		"picwidth,picheight,picsytle,cssname,concat('"+rodmomCPId+"',templateid),title,titlecolor,showstate,portletwidth,portletheight,titlepic,titletype" +
		" from cms_portletinstance4 where id in " +
		"(select portletId from cms_placeholder where  channelid like '%," + oldSite.get("id")+"'))";
		String insert_$cms_portletinstance_c$_sql1 = "insert into cms_portletinstance_c (select  concat('"+rodmomCPId+"',id),concat('"+rodmomCPId+"',templateid)," +
				"title,titlecolor,portletwidth,portletheight,titlepic,titletype,object,objecttype" +
				" from cms_portletinstance_c where id in " +
		"(select portletId from cms_placeholder where  channelid like '%," + oldSite.get("id")+"'))";
		//**************************************************更新模板站点的被复制此数
		Integer clone_num = (Integer)oldSite.get("clone_num");
		clone_num++;
		String upSiteCloneNum = "UPDATE cms_site SET clone_num = "+clone_num+" where id = '"+ oldSite.get("id") + "'";
		String[] sqls = new String[27];
		sqls[0] = insert_$cms_site$_sql;
		sqls[1] = insert_$sys_auth$_sql;
		sqls[2] = insert_$cms_channel$_sql;
		sqls[3] = insert_$cms_layout$_sql;
		sqls[4] = insert_$cms_lookfeel$_sql;
		sqls[5] = insert_$cms_template$_sql;
		sqls[6] = insert_$cms_artgroup$_sql;
		sqls[7] = insert_$cms_article_group$_sql;
		sqls[8] = insert_$ext_productgroup$_sql;
		sqls[9] = insert_$ext_products$_sql;
		sqls[10] = insert_$cms_placeholder$_sql;
		sqls[11] = insert_$cms_portletinstance$_sql;
		sqls[12] = insert_$cms_portletinstance1$_sql;
		sqls[13] = insert_$cms_portletinstance2$_sql;
		sqls[14] = insert_$cms_portletinstance3$_sql;
		sqls[15] = insert_$cms_portletinstance4$_sql;
		sqls[16] = insert_$sys_auth$_sql1;
		
		sqls[17] = insert_$cms_placeholder$_sql1; 
		sqls[18] = insert_$cms_portletinstance$_sql1;
		sqls[19] = insert_$cms_portletinstance1$_sql1;
		sqls[20] = insert_$cms_portletinstance2$_sql1;
		sqls[21] = insert_$cms_portletinstance3$_sql1;
		sqls[22] = insert_$cms_portletinstance4$_sql1;
		sqls[23] =insert_$cms_function$_sql;
		sqls[24] = upSiteCloneNum;
		sqls[25] =insert_$cms_portletinstancec$_sql;
		sqls[26] = insert_$cms_portletinstance_c$_sql1;
//		for(int i = 0; i < sqls.length;i++){
//			System.out.println(sqls[i]);
//		}
		
		sitedao.cloneSite(sitedao.creatCloneArticleSQL((String)oldSite.get("id"),newSiteId , destSitePath,rodmomCPId));
		sitedao.cloneSite(sqls);
		
	}

	public PageBean getCpSites(int currentPage, int pageSize,String site) {
		return sitedao.getCpSites(currentPage,pageSize,site);
	}

	public List getSitesBySiteUrl(String url) {
		return sitedao.getSitesBySiteUrl(url);
	}
	
}
